package com.jweb.framework.core.config;

import java.util.Collection;
import java.util.Properties;

import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.xml.AbstractSingleBeanDefinitionParser;
import org.springframework.beans.factory.xml.ParserContext;
import org.springframework.util.StringUtils;
import org.springframework.util.xml.DomUtils;
import org.w3c.dom.Element;

import com.jweb.framework.core.impl.DefaultProcessing;


public class TopProcedureParser extends AbstractSingleBeanDefinitionParser {
	
	protected Class getBeanClass(Element element){
		return DefaultProcessing.class; 
	}
	
	protected void doParse(Element element , ParserContext parserContext , BeanDefinitionBuilder beanDefinitionBuilder) {
		
		String id = element.getAttribute("id");
		if(!StringUtils.hasText(id)){
			parserContext.getReaderContext().error("'id ' is required ", element);
		}
		
		String template = element.getAttribute("template");
		if(!StringUtils.hasText(template)){
			parserContext.getReaderContext().error("'template ' is required ", element);
		}
		
		String interceptors = element.getAttribute("interceptors");
		if(!StringUtils.hasText(interceptors)){
			parserContext.getReaderContext().error("'interceptors ' is required ", element);
		}
		
		beanDefinitionBuilder.addPropertyValue("name", id);
		beanDefinitionBuilder.addPropertyValue("executor", template);
		beanDefinitionBuilder.addPropertyValue("interceptors", interceptors);
		
		String inputFields = element.getAttribute("input-fields");
		if(StringUtils.hasText(inputFields)){
			beanDefinitionBuilder.addPropertyValue("inputFields", inputFields);
		}
		String outputFields = element.getAttribute("output-fields");
		if(StringUtils.hasText(outputFields)){
			beanDefinitionBuilder.addPropertyValue("outputFields", outputFields);
		}
		
		Element actionElement = DomUtils.getChildElementByTagName(element , "jservices");
		Collection actionsCollection = ActionParser.createActions(actionElement,  parserContext);
		beanDefinitionBuilder.addPropertyValue("jservices", actionsCollection);
		
		Element attributesElement = DomUtils.getChildElementByTagName(element, "attributes");
		if(attributesElement != null){
			Properties properties = parserContext.getDelegate().parsePropsElement(attributesElement);
			beanDefinitionBuilder.addPropertyValue("attriubtes", properties);
		}
	}
}
